from pyecharts.charts import Pie
from pyecharts import options as opts
from sc.ZDao import connect_mysql
import pymysql


def generate_job_distribution_pie():
    # 连接数据库
    db = connect_mysql()
    if not db:
        print("数据库连接失败")
        return

    try:
        # 创建游标
        with db.cursor() as cur:
            # 查询各城市岗位数量
            sql = """
            SELECT 
                SUBSTRING_INDEX(job_loc, '·', 1) AS city,
                COUNT(*) AS job_count
            FROM jobs
            WHERE job_name LIKE '%Java%' OR job_name LIKE '%java%'
            GROUP BY SUBSTRING_INDEX(job_loc, '·', 1)
            ORDER BY job_count DESC
            LIMIT 5
            """
            print("执行SQL:", sql)

            cur.execute(sql)
            results = cur.fetchall()

            # 准备数据（按您图片中的颜色顺序）
            data = []
            color_sequence = ['#5470C6', '#91CC75', '#FAC858', '#EE6666', '#73C0DE']
            for row in results:
                data.append((row['city'], row['job_count']))
                print(f"城市: {row['city']}, 岗位数: {row['job_count']}")

            # 创建饼图（完全按照参考图样式）
            pie = (
                Pie(init_opts=opts.InitOpts(width="800px", height="600px"))
                .add(
                    "",
                    data,
                    radius=["30%", "70%"],
                    center=["50%", "50%"],
                    label_opts=opts.LabelOpts(
                        formatter="{b}: {d}%",  # 显示城市名和百分比
                        font_size=12,
                        color="#333"
                    ),
                    itemstyle_opts=opts.ItemStyleOpts(
                        border_width=1,
                        border_color="#fff"
                    )
                )
                .set_colors(color_sequence)  # 设置指定颜色序列
                .set_global_opts(
                    title_opts=opts.TitleOpts(
                        title="各城市-岗位占比图",
                        pos_left="center",
                        title_textstyle_opts=opts.TextStyleOpts(
                            font_size=20,
                            color="#333",
                            font_weight="bold"
                        )
                    ),
                    legend_opts=opts.LegendOpts(
                        orient="vertical",
                        pos_top="15%",
                        pos_right="5%",
                        item_width=10,
                        item_height=10,
                        textstyle_opts=opts.TextStyleOpts(
                            font_size=12
                        )
                    ),
                    tooltip_opts=opts.TooltipOpts(
                        trigger="item",
                        formatter="{a} <br/>{b}: {c} ({d}%)"
                    )
                )
            )

            # 渲染图表
            output_file = "piera.html"
            pie.render(output_file)
            print(f"\n✅ 岗位分布饼图已生成: {output_file}")

    except pymysql.Error as e:
        print(f"数据库操作出错: {e}")
    finally:
        if db:
            db.close()


if __name__ == "__main__":
    generate_job_distribution_pie()